import json
import re

from django import http
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User


class IoginView(View):
    # 登录  POST api/v1.0/session
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')

        if not all([mobile, password]):
            return http.JsonResponse({'errno': '4103', 'errmsg': '缺少必传参数'})

        if not re.match(r'^1([38]\d|5[0-35-9]|7[3678])\d{8}$', mobile):
            return http.JsonResponse({"errno": "4103", "errmsg": "参数mobile错误"})

        if not re.match(r'^[0-9a-zA-Z-_]{6,18}$', password):
            return http.JsonResponse({"errno": "4103", "errmsg": "参数password错误"})

        user = authenticate(request=request, username=mobile, password=password)
        if not user:
            return http.JsonResponse({'errno': '4103', 'errmsg': '登陆失败'})
        login(request, user)
        return http.JsonResponse({'errno': '0', 'errmsg': '登陆成功'})

    # 验证是否登录   api/v1.0/session
    def get(self, request):
        if request.user.is_authenticated:
            # 已登录：
            data = {
                'name': request.user.username,
                'user_id': request.user.id
            }
            return http.JsonResponse({'errno': '0', 'errmsg': '已登录', 'data': data})
        else:
            # 未登录
            return http.JsonResponse({'errno': '4101', 'errmsg': '未登录'})

    def delete(self, request):
        logout(request)
        return http.JsonResponse({'errno': '0', 'errmsg': '已登出'})


class RegisterUserView(View):
    # 注册  api/v1.0/users
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')  # 手机号
        phonecode = json_dict.get('phonecode')  # 短信验证码
        password = json_dict.get('password')  # 密码
        if not all([mobile, phonecode, password]):
            return http.JsonResponse({'errno': '4103', 'errmsg': '缺少必传参数'})

        if not re.match(r'^1([38]\d|5[0-35-9]|7[3678])\d{8}$', mobile):
            return http.JsonResponse({"errno": "4103", "errmsg": "参数mobile错误"})

        if not re.match(r'^[0-9a-zA-Z-_]{6,18}$', password):
            return http.JsonResponse({"errno": "4103", "errmsg": "参数password错误"})

        redis_conn = get_redis_connection('verification')
        sms_server = redis_conn.get('sms_%s' % mobile)
        sms_server = sms_server.decode()
        if phonecode != sms_server:
            return http.JsonResponse({'errno': '4103', 'errmsg': '短信验证码错误'})

        user = User.objects.create_user(
            mobile=mobile,
            password=password,
            username=mobile,
            avatar=settings.USER_DEFUAL_IMG
        )

        login(request, user)
        return http.JsonResponse({'errno': '0', 'errmsg': '注册成功'})
